package cn.shop.dys.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.mrwujay.cascade.model.CityModel;
import com.mrwujay.cascade.model.DistrictModel;
import com.mrwujay.cascade.model.ProvinceModel;
import com.mrwujay.cascade.service.XmlParserHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import cn.shop.dys.widget.AddressAddDialog;
import cn.shop.lib_common.CommonUtil;
import cn.shop.dys.R;
import cn.shop.dys.constant.CommonConstant;
import cn.shop.dys.constant.SPConstant;
import cn.shop.dys.util.SPUtil;
import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;


/**
 * 增加用户地址
 * Created by sunjian on 2016/4/19.
 */
public class UserDetailsAddressAddFragment extends BaseFragment implements OnWheelChangedListener, View.OnClickListener {
    @ViewInject(R.id.tv_user_simple_address)
    private TextView mUserSimpleAddress;
    @ViewInject(R.id.ll_user_simple_address)
    private View mLlUserSimpleAddress;
    @ViewInject(R.id.et_user_detail_address)
    private EditText mUserDetailAddress;
    @ViewInject(R.id.et_user_name)
    private EditText mUserName;
    @ViewInject(R.id.et_user_phone)
    private EditText mUserPhone;
    @ViewInject(R.id.et_user_zip_code)
    private EditText mUserZipCode;
    @ViewInject(R.id.bt_address_save)
    private Button mAddressSave;
    @ViewInject(R.id.cb_is_defalut_address)
    private CheckBox mIsDefalutAddress;
    private Context mContext;
    private String mProvince = "不详";
    private String mCity = "不详";
    private String mAddressArea = "不详";
  //  private AlertDialog mDialog;
    private Button mCancel;
    private Button mConfirm;
    private AddressAddDialog mDialog;

    @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_user_details_address_add, null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
       // getActivity().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        mContext = getActivity();
        init();
    }

    private void init() {
        initDialog();
        initEvent();
    }

    private void initDialog() {
       /* AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        mDialog = builder.create();*/
        View view = View.inflate(mContext, R.layout.address_list_add_dialog, null);
        mViewProvince = (WheelView) view.findViewById(R.id.id_province);
        mViewCity = (WheelView) view.findViewById(R.id.id_city);
        mViewDistrict = (WheelView) view.findViewById(R.id.id_district);
        mCancel = (Button) view.findViewById(R.id.id_cancel);
        mConfirm = (Button) view.findViewById(R.id.id_confirm);
        setUpListener();
        setUpData();
        mDialog = new AddressAddDialog(mContext,0,0,view, R.style.address_dialog);
       // mDialog.setView(view, 0, 0, 0, 0);
      //  mDialog.show();
    }

    private void initEvent() {
        mLlUserSimpleAddress.setOnClickListener(this);
        mAddressSave.setOnClickListener(this);
        mCancel.setOnClickListener(this);
        mConfirm.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_user_simple_address:
                mDialog.show();
                break;
            case R.id.bt_address_save:
                saveAddress();
                break;
            case R.id.id_cancel:
                mDialog.dismiss();
                break;
          /*  private String mProvince = "不详";
            private String mCity = "不详";
            private String mAddressArea = "不详";*/
            case R.id.id_confirm:
                mProvince=mCurrentProviceName;
                mCity=mCurrentCityName;
                mAddressArea=mCurrentDistrictName;
                mUserSimpleAddress.setText(mProvince+mCity+mAddressArea);
                mDialog.dismiss();
                break;
        }
    }
    /**
     * 更新默认
     * 作者:孙建
     * created at 2016/4/21 19:18
     */
    public void updateAddressDefalut(final String consigneeName, final String consigneePhone, final String consigneeDetailAddress, final String consigneeZipCode, final String isDefalut) {
        // String isDefalut = mIsDefalutAddress.isChecked() ? "1" : "0";
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        params.addHeader("userid", SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID));
        /*if (isDefalut.equals("1")) {
            // params.addQueryStringParameter("id",mAddressInfo.getId()+"");
        }*/
        mHttpUtils.send(HttpRequest.HttpMethod.GET, CommonConstant.HOST_ADDRESSDEFAULT, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if (response.equals("addressDefault")) {
                                   /* CommonUtil.showToast(mContext, "保存默认地址成功");
                                    onBackPressed();*/
                                    saveLastAddress(consigneeName, consigneePhone, consigneeDetailAddress, consigneeZipCode, isDefalut);
                                } else {
                                    String error = jsonObject.getString("error");
                                    String error_code = jsonObject.getString(CommonConstant.ERROR_CODE);
                                    if (error_code.equals(CommonConstant.ERROR_CODE_NO_USERID_ON_REQUEST_HEAD)) {
                                        CommonUtil.showToast(mContext, error);
                                    } else if (error_code.equals(CommonConstant.ERROR_CODE_UNLOGIN)) {
                                        CommonUtil.showToast(mContext, error);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        } else {
                            CommonUtil.showToast(mContext, "请求失败:错误码为" + statusCode);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(mContext, "网络未连接:" + msg);
                    }
                });
    }

    /**
     * 保存地址
     * 作者:孙建
     * created at 2016/4/21 19:18
     */
    public void saveAddress() {
        String consigneeName = mUserName.getText().toString().trim();
        String consigneePhone = mUserPhone.getText().toString().trim();
        String consigneeDetailAddress = mUserDetailAddress.getText().toString().trim();
        String consigneeZipCode = mUserZipCode.getText().toString().trim();
        String isDefalut = mIsDefalutAddress.isChecked() ? "1" : "0";
        if (TextUtils.isEmpty(consigneeName) || TextUtils.isEmpty(consigneePhone)
                || TextUtils.isEmpty(consigneeDetailAddress) || TextUtils.isEmpty(consigneeZipCode)
                || TextUtils.isEmpty(mProvince) || TextUtils.isEmpty(mCity) || TextUtils.isEmpty(mAddressArea)) {
            CommonUtil.showToast(mContext, "请填完整收货地址信息");
            return;
        }
        if (isDefalut.equals("1")) {
            updateAddressDefalut(consigneeName, consigneePhone, consigneeDetailAddress, consigneeZipCode, isDefalut);
        } else {
            saveLastAddress(consigneeName, consigneePhone, consigneeDetailAddress, consigneeZipCode, isDefalut);
        }
    }

    /**
     * 清除输入
     * 作者:孙建
     * created at 2016/4/21 19:19
     */
    private void clearInput() {
        mUserName.setText("");
        mUserDetailAddress.setText("");
        mUserPhone.setText("");
        mUserZipCode.setText("");
        mIsDefalutAddress.setChecked(false);
        mUserSimpleAddress.setText("省市区");
    }

    /**
     * 保存最终的地址
     * 作者:孙建
     * created at 2016/4/21 19:19
     */
    private void saveLastAddress(String consigneeName, String consigneePhone, String consigneeDetailAddress, String consigneeZipCode, String isDefalut) {
        mHttpUtils.configDefaultHttpCacheExpiry(0);
        mHttpUtils.configTimeout(10000);
        RequestParams params = new RequestParams();
        params.addHeader("userid", SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID));
        params.addBodyParameter("name", consigneeName);
        params.addBodyParameter("phoneNumber", consigneePhone);
        params.addBodyParameter("province", mProvince);
        params.addBodyParameter("city", mCity);
        params.addBodyParameter("addressArea", mAddressArea);
        params.addBodyParameter("addressDetail", consigneeDetailAddress);
        params.addBodyParameter("zipCode", consigneeZipCode);
        params.addBodyParameter("isDefault", isDefalut);
        mHttpUtils.send(HttpRequest.HttpMethod.POST, CommonConstant.HOST_ADDRESSSAVE, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        int statusCode = responseInfo.statusCode;
                        if (statusCode == 200) {
                            String result = responseInfo.result;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String response = jsonObject.getString("response");
                                if (response.equals("addresssave")) {
                                    /*String addressList = jsonObject.getString("addressList");
                                    List<AddressInfo> addressInfos = mGson.fromJson(addressList,
                                            new TypeToken<List<AddressInfo>>() {
                                            }.getType());
                                    for (AddressInfo addressInfo : addressInfos) {
                                        if(addressInfo.getIsDefault()==1){

                                        }
                                    }*/
                                    clearInput();
                                    CommonUtil.showToast(mContext, "保存成功");
                                    onBackPressed();
                                } else {
                                    String error = jsonObject.getString("error");
                                    String error_code = jsonObject.getString(CommonConstant.ERROR_CODE);
                                    if (error_code.equals(CommonConstant.ERROR_CODE_NO_USERID_ON_REQUEST_HEAD)) {
                                        CommonUtil.showToast(mContext, error);
                                    } else if (error_code.equals(CommonConstant.ERROR_CODE_UNLOGIN)) {
                                        CommonUtil.showToast(mContext, error);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            CommonUtil.showToast(mContext, "请求失败:错误码为" + statusCode);
                        }

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        CommonUtil.showToast(mContext, "网络未连接:" + msg);
                    }

                });
    }

    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
        // 添加onclick事件
        //    mBtnConfirm.setOnClickListener(this);
    }

    private void setUpData() {
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(mContext, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(5);
        mViewCity.setVisibleItems(5);
        mViewDistrict.setVisibleItems(5);
        updateCities();
        updateAreas();
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(mContext, areas));
        mViewDistrict.setCurrentItem(0);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(mContext, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    /**
     * 所有省
     */
    private String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    private Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    private Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    private Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    private String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    private String mCurrentCityName;
    /**
     * 当前区的名称
     */
    private String mCurrentDistrictName = "";

    /**
     * 当前区的邮政编码
     */
    private String mCurrentZipCode = "";

    /**
     * 解析省市区的XML数据
     */

    private void initProvinceDatas() {
        List<ProvinceModel> provinceList = null;
        AssetManager asset = getActivity().getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            //*/ 初始化默认选中的省、市、区
            if (provinceList != null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getName();
                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0).getDistrictList();
                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
            //*/
            mProvinceDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {

        }
    }
}
